var dataSource;

$(document).ready(function() {
    var grid = $('#grid');
    grid.on('click', '.seeImage', verImagen);
    dataSource = new kendo.data.DataSource({
        transport: {
            create: {
                url: appBosch.crud.create,
                dataType: "json"
            },
            read: {
                url: appBosch.crud.read,
                dataType: "json"
            },
            update: {
                url: appBosch.crud.update,
                dataType: "json"
            },
            destroy: {
                url: appBosch.crud.destroy,
                dataType: "json"
            },
            parameterMap: function(options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'create':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'read':
                        break;
                    case 'update':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'destroy':
                        params = {id: options.models[0].id};
                }
                return params;
            }
        },
        batch: true,
        schema: {
            model: {
                id: "id",
                fields: {
                    line_id: {
                        defaultValue: appBosch.lineId
                    },
                    name: {
                        editable: true,
                        nullable: false,
                        type: 'number',
                        validation: {
                            required: true,
                            min: 0
                        }
                    },
                    description: {
                        editable: true,
                        nullable: false,
                        validation: {
                            required: true,
                            min: 1
                        }
                    },
                    vigenciaCertification: {
                        type: 'number',
                        defaultValue: 3,
                        validation: {
                            required: true,
                            min: 1,
                            max: 5
                        }
                    },
                    vigenciaProccess: {
                        type: 'number',
                        defaultValue: 2,
                        validation: {
                            required: true,
                            min: 1,
                            max: 8
                        }
                    },
                    maxProccess: {
                        type: 'number',
                        defaultValue: 8,
                        validation: {
                            required: true,
                            min: 1,
                            max: 8
                        }
                    },
                    notification_end: {
                        type: 'number',
                        defaultValue: 5,
                        validation: {
                            required: true,
                            min: 1,
                            max: 14
                        }
                    },
                    notification_life: {
                        type: 'number',
                        defaultValue: 90,
                        validation: {
                            required: true,
                            min: 1,
                            max: 360
                        }
                    },
                    optional: {
                        editable: true,
                        nullable: false,
                        type: 'boolean'
                    },
                    lock_days: {
                        editable: true,
                        nullable: false,
                        type: 'number',
                        defaultValue: 180,
                        validation: {
                            required: true,
                            min: 1
                        }
                    },
                    img: {
                        type: "string",
                        editable: true,
                        nullable: true
                    }
                }
            }
        }
    });
    grid.kendoGrid({
        toolbar: [
            {
                name: "create",
                text: "Agregar Operación"
            },
            {
                name: "excel",
                text: "Exportar a Excel"
            },
            {
                name: "pdf",
                text: "Exportar a PDF"
            }
        ],
        excel: {
            allPages: true,
            fileName: "Operaciones.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Operaciones.pdf"
        },
        scrollable: true,
        resizable: true,
        columnMenu: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        sortable: true,
        dataSource: dataSource,
        columns: [
            {
                field: "name", 
                title: "Orden", 
                format: "n0",
                template: '#=kendo.toString(name, "n0")#',
                width: 50
            },
            {
                field: "description", title: "Descripción",
                template: '<code>#=description#</code>'
            },
            {
                field: "vigenciaProccess",
                title: "Vigencia del proceso de certificación [semanas]",
                format: "n0",
                template: '#=kendo.toString(vigenciaProccess, "n0")# semanas',
                width: 120
            },
            {
                field: "maxProccess",
                title: "Máxima vigencia del proceso de certificación [semanas]",
                format: "n0",
                template: '#=kendo.toString(maxProccess, "n0")# semanas',
                width: 120
            },
            {
                field: "vigenciaCertification", 
                title: "Vigencia de la certificación [años]", 
                format: "n0",
                template: '#=kendo.toString(vigenciaCertification, "n0")# años',
                width: 120
            },
            {
                field: "notification_end", 
                title: "Notificación fin de proceso[dias]", 
                format: "n0",
                template: '#=kendo.toString(notification_end, "n0")# dias',
                width: 120
            },
            {
                field: "notification_life", 
                title: "Notificación fin de certificación[dias]", 
                format: "n0",
                template: '#=kendo.toString(notification_life, "n0")# dias',
                width: 120
            },
            {
                field: "optional", 
                title: "Opcional",
                template: '#if(optional === true){# <i class="fa fa-2x fa-check"></i>#}#',
                width: 50
            },
            {
                field: 'lock_days',
                title: 'Dias de bloqueo'
            },
            {
                field: "img",
                title: "Imagen",
                editor: imgEditor,
                template: '#if(img !== "" && img !== null && img !== undefined){# <button class="seeImage k-button k-button-icontext">Ver imagen</button>#}#',
                width: 150
            },
            {command: [
                    {name: "preguntas", text: "?", click: showQuestions},
                    {text: "Temas", click: showConfig},
                    {
                        name: "edit",
                        text: {
                            edit: "",
                            update: "",
                            cancel: ""
                        }
                    },
                    {
                        name: "destroy",
                        text: ""
                    }], title: "&nbsp;"}],
        editable: {
            confirmation: "¿Estas seguro que deseas eliminar está Operación?",
            mode: "popup"
        }
    });
});

function showConfig(e)
{
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var workstationId = dataItem.id;
    var parts = [appBosch.urlConfig, workstationId, appBosch.lineId, appBosch.areaId, appBosch.moeId];
    var url = parts.join('/');
    $(location).attr('href', url);
}

function showQuestions(e)
{
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var id = dataItem.id;
    var url = appBosch.crud.questions + '/4/' + appBosch.moeId + '/' + appBosch.areaId + '/' + appBosch.lineId + '/' + id;
    $(location).attr('href', url);
}

function imgEditor(container, options) {
    var input = $("<input type='file' id='image' />");
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoUpload({
        async: {
            saveUrl: appBosch.upload + '/1'
        },
        localization: {
            select: "Seleccionar...",
            headerStatusUploaded: "",
            headerStatusUploading: "",
            statusUploaded: "",
            statusUploading: ""
        },
        //files: files
        success: function () {
            options.model.set('img', 'Ok');
        },
        multiple: false
    });
}

function verImagen (e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSource.getByUid(dataItem.data('uid'));
    $("<div><img src='" + dataItem.img + "?" + Math.floor((Math.random() * 10) + 1).toString() + "' width='400px' /></div>").kendoWindow({
        width: "400px",
        title: "Imagen",
        actions: [
            "Close"
        ]
    }).data("kendoWindow").open().center();
}